import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import Qs from 'qs'

Vue.use(Vuex)

const store =  new Vuex.Store({
  state: {
    activeMenu: 'Main', //当前菜单
    loggedIn: false, //是否登录
    username: '', //用户名称
    access_token: '',
    userRoles: [],
    userId: null,
    photoUrl: null,
  },
  getter: {

  },
  mutations: {
    changeMenu (state, payload) {
      state.activeMenu = payload.activeMenu
    },
    changeLogin (state, payload) {
      state.loggedIn = payload.loggedIn
      state.username = payload.username
      state.access_token = payload.access_token
    },
    logout (state) {
      state.loggedIn = false
      state.username = ''
      state.access_token = ''
      state.userRoles = []
      state.userId = null
      state.photoUrl = null
    },
  },
  actions: {
    // 登录验证
    loginAsync ({commit}, loginBody) {
      return axios.get('/users/search/existsByNameAndPassword', {
        params: {
          name: loginBody.name,
          password: loginBody.password
        }
      })
    },

    // 获取username通过id
    async getUsernameById(context, id) {
      let username = ''
      const {data} = await axios.get('/users/search/getUsernameById', { params: {id} })
      data ? username = data : ''
      return username
    },

    // 获取username photoUrl 通过userId
    async getUsernameAndPhotoUrlById(context, id) {
      const {data} = await axios.get(`/users/${id}`)
      const obj = data ? {username: data.username, photoUrl: data.photoUrl} : {username: '', photoUrl: ''}
      return obj
    },

    // 获取access_token
    accessTokenAsync ({commit}, payload) {
      return axios.post('/oauth/token', {}, {
        params: {
          grant_type: 'password',
          client_id: 'site',
          client_secret: 'site',
          username: payload.username,
          password: payload.password
        }
      })
    },

    // 通过用户Id获取用户信息
    loginInfoByIdAsync (context, userId) {
      return axios.get(`/users/${userId}`)
    },

    // 通过用户名获取信息
    setUserInfoByUsername ({commit, state}, username) {
      axios.get('/users/search/findByUsername', {
        params: {
          username
        }
      })
      .then(res => {
        state.userId = res.data.id
        state.userRoles = res.data.authorities
        state.photoUrl = res.data.photoUrl
      })
    },


    // 用户注册
    regAsync ({commit}, regBody) {
      return axios.post('/users', {
        username: regBody.name,
        password: regBody.password,
        email: regBody.email,
        userRoles: [],
        createTime: new Date().getTime()
      })
    },

    // 获取根category
    rootCategoriesAsync({commit}) {
      return axios.get('/blogCategories/search/findByParentBlogCategoryIdIsNull', {
        params: {
          sort: 'createTime,desc'
        }
      })
    },

    // 创建category
    categoryCreationAsync({state}, categoryBody) {
      return axios.post('/blogCategories', {
        authorId: state.userId,
        createTime: new Date().getTime(),
        name: categoryBody.name,
        photoUrl: categoryBody.photoUrl,
        description: categoryBody.description,
        parentBlogCategory: categoryBody.parentUri,
      })
    },

    // 创建博文
    blogCreationAsync({state}, blogBody) {
      return axios.post('/blogs', {
        'createTime': new Date().getTime(),
        'content': blogBody.content,
        'authorId': state.userId,
        'title': blogBody.title,
        'description': blogBody.description,
        'parentCategory': blogBody.parentCategory
      })
    },

    // 获取博文列表通过类别ID
    blogListAsync (context, categoryId) {
      return axios.get('/blogs/search/findByParentCategoryId', {
        params: {
          parentCategory: categoryId
        }
      })
    },

    // 获取博文列表排序分页
    blogPagingAndSorting (context, payload) {
      return axios.get('/blogs', {
        params: {
          page: payload.page ? payload.page : 0,
          size: payload.size ? payload.size : '',
          sort: payload.sort ? payload.sort : '',
        }
      })
    },

    // 获取博文
    blogDetailAsync (context, blogId) {
      return axios.get(`/blogs/${blogId}`)
    },

    // 评论博文
    blogCommentAsync ({state}, commentBody) {
      return axios.post('/blogComments', {
        comment: commentBody.comment,
        commentTime: new Date().getTime(),
        userId: state.userId,
        targetBlog: commentBody.blogUri,
      })
    },

    // 获取博文评论
    targetBlogCommentAsync (context, targetBlogId) {
      return axios.get('/blogComments/search/findByTargetBlogId', {
        params: {
          targetBlog: targetBlogId,
          sort: 'commentTime,desc'
        }
      })
    },

    // 回复博文评论
    replyBlogCommentAsync ({state}, replyBody) {
      return axios.post('/blogCommentReplies', {
        content: replyBody.content,
        createTime: new Date().getTime(),
        userId: state.userId,
        replayUserId: replyBody.replayUserId,
        targetBlogComment: replyBody.commentUri
      })
    },

    // 获取博文评论回复
    commentRepliesAsync (context, commentId) {
      return axios.get('/blogCommentReplies/search/findByTargetBlogCommentId', {
        params: {
          targetBlogComment: commentId,
          sort: 'commentTime,asc'
        }
      })
    },

    // 获取最新4篇博文
    queryNewest4 (context) {
      return axios.get('/blogs/search/queryFirst4ByOrderByCreateTimeDesc')
    },

    // 获取评论数通过blog id
    async queryCommentCountByTargetBlogId (context, blogId) {
      const {data} = await axios.get('/blogComments/search/countByTargetBlogId', {
        params: {
          targetBlog: blogId
        }
      })
      let count = data ? data : 0
      return count
    },

    // 获取城市信息
    queryCityInfo () {
      return axios.get('http://restapi.amap.com/v3/ip?key=10c090edb16204ed58ef87943107c2df')
    },

    // 通过城市 code获取天气信息
    queryCityWeatherByCityCode (context, cityCode) {
      console.log('cityCode', cityCode);
      return axios.get('http://restapi.amap.com/v3/weather/weatherInfo?city=' + cityCode + '&key=10c090edb16204ed58ef87943107c2df&extensions=all')
    },

    // 获取ip地址
    async queryIPAddr (context) {
      const {data} = await axios.get('http://freegeoip.net/json/')
      const ip = data.ip ? data.ip : ''
      return ip
    },

    // 获取游客信息
    async queryGuestInfo ({dispatch}) {
      const info = await axios.get('http://freegeoip.net/json/')

      const rank = await dispatch('queryRankByIp', info.data.ip)

      const guest = {
        ip: info.data.ip,
        countryName: info.data.country_name,
        reginName: info.data.region_name,
        city: info.data.city,
        createTime: new Date().getTime(),
        rank
      }
      return guest
    },
    // 保存游客信息
    async saveGuest ({dispatch}) {
      const info = await dispatch('queryGuestInfo')
      axios.post('/guests', info)
        .then(res => {
          console.log('成功保存游客信息');
        })
        .catch (err => {
          console.error('保存游客信息出错');
        })

    },
    // 查询游客排名
    async queryRankByIp ({dispatch}, ip) {
      const {data} = await axios.get('/guests/search/rownumByIpOrderByCreateTimeAsc', {
        params: {
          ip: ip
        }
      })
      const rank = data ? data : 0
      return rank
    },

    // 添加查看量
    viewBlogAsync (context, payload) {
      return axios.post('/blogViews', {
        createTime: new Date().getTime(),
        ip: payload.ip,
        targetBlog: payload.uri
      })
    },

    async queryCountViewByBlogId (context, blogId) {
      const {data} = await axios.get('/blogViews/search/countByTargetBlogId', {
        params: {
          targetBlog: blogId,
        }
      })
      const count = data ? data : 0
      return count
    },

    // 获取验证码
    getVerityAsync (context) {
      return axios.get('/getVerify')
    },

    // 验证码验证
    async checkVerityAsync (context, inputStr) {
      const {data} = await axios.post('/checkVerify', {inputStr})
      return data
    },

    // 创建歌单
    createMusicListAsync ({state}, name) {
      return axios.post('/musicLists', {
        createBy: state.userId,
        musicContian: [],
        createTime: new Date().getTime(),
        name: name,
        photoURL: '',
      })
    },
    // 获取创建歌单列表
    queryMusicListAsync ({state}) {
      return axios.get('/musicLists/search/findByCreateBy', {
        params: {
          createBy: state.userId
        }
      })
    },
    // 删除歌单列表
    rmMusicListAsync (context, id) {
      return axios.delete(`/musicLists/${id}`)
    },
    // 获取歌单列表
    getMusicListAsync (context, payload) {
      return axios.get('/musicLists', {
        params: {
          sort: 'createTime,asc',
          size: payload.size,
          page: payload.page
        }
      })
    },
    // 上传歌单
    uploadMusicAsync ({state}, payload) {
      return axios.post('/musics', {
        createTime: new Date().getTime(),
        description: payload.description,
        name: payload.name,
        qualityURL: payload.qualityURL,
        singer: payload.singer,
        uploadBy: state.userId,
      })
    },
    // 最新上传
    queryLastUploadMusics (context, payload) {
      return axios.get('/musics', {
        params: {
          sort: 'createTime,desc',
          page: payload.page,
          size: payload.size,
        }
      })
    },
    // 获取排行榜
    topMusicAysnc (context, topSize) {
      return axios.get('/musics', {
        params: {
          sort: 'createTime,desc',
          page: 0,
          size: topSize
        }
      })
    },

    // 添加歌曲到歌单
    addMusicToMusicListAsync (context, payload) {
      return axios.patch(`/musicLists/${payload.musicListId}`, {
        musicContian: [payload.musicUri]
      })
    }
  },
})

// 请求拦截器
axios.interceptors.request.use(function (config) {
    if ((!config.url || !config.url.includes('/oauth/token')) && store.state.access_token) {
      config.params = Object.assign(config.params ? config.params : {}, {access_token: store.state.access_token})
    }
    return config;
  }, function (error) {
    return Promise.reject(error);
  });
axios.interceptors.response.use(function (response) {
    return response;
  }, function (error) {
    console.log('error', error);
    return Promise.reject(error);
  });

export default store
